package lib.parallel;

import com.google.common.base.Stopwatch;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * Created by apple on 2018/7/1.
 */
public class PallelerStream {

    public static long sequentialSum(long n) {
        return Stream.iterate(1L, i -> i + 1)
                .limit(n)
                .reduce(0L, Long::sum);
    }

    /**
     * parallel one
     * @param n
     * @return
     */
    public static long sequentialParallelSum(long n) {
        return Stream.iterate(1L, i -> i + 1)
                .limit(n).parallel()
                .reduce(0L, Long::sum);
    }

    public static long iterativeSum(long n) {
        long result = 0;
        for (long i = 1L; i <= n; i++) {
            result += i;
        }
        return result;
    }

    @Test
    public void testSum() {
        Stopwatch stopWatch = Stopwatch.createStarted();
        sequentialSum(100000000);
        stopWatch.stop();
        System.out.println(stopWatch.elapsed(TimeUnit.MILLISECONDS));
    }

    @Test
    public void testSumParall() {
        Stopwatch stopWatch = Stopwatch.createStarted();
        sequentialParallelSum(100000);
        stopWatch.stop();
        System.out.println(stopWatch.elapsed(TimeUnit.MILLISECONDS));
    }

    @Test
    public void testIterativeSum() {
        Stopwatch stopWatch = Stopwatch.createStarted();
        iterativeSum(100000000);
        stopWatch.stop();
        System.out.println(stopWatch.elapsed(TimeUnit.MILLISECONDS));
    }
}
